/**
 * Created by sami on 30/05/2017.
 */
import React, {Component, PropTypes} from 'react';
import {
    AppRegistry,
    StyleSheet,
    View,
		Image,
    TouchableHighlight,
		Alert,
		BackHandler
} from 'react-native';
import {
    Container,
    Header,
    Title,
    Content,
    Footer,
    FooterTab,
    Button,
    Left,
    Right,
    Icon,
    Item,
    Input,
    Toast,
    List,
    ListItem,
    Thumbnail,
    Text,
    Body,
    Spinner,
		Drawer
} from 'native-base';
//import Video from 'react-native-video';
import styles from './styles.js';
import Swiper from 'react-native-swiper';
import CouponItem from './components/CouponItem.js';
import TwoCoupons from './components/TwoCoupons.js';
import SideBar from './components/SideBar.js';
import Util from './utils.js';
export default class MainScreen extends Component {
		drawer = null;
    constructor(props) {
        super(props);
        this.state = {keyword: "", suggestResult: [],twoCouponsList:[], page: 0, showToast: false,showLoading:false,twoItemsOneRow:true,drawerIsOpen:false};
    }

		componentDidMount = function (){
				this.loadSuggest();
				BackHandler.addEventListener('hardwareBackPress', function() {
						console.log("hardwareBackPress");
						if(this.state.drawerIsOpen){
								this.closeDrawer();
								return true;
						}

				}.bind(this));
		}

    static navigationOptions = {
        title: 'MainScreen'
    };

		// getDrawerState = () =>{
		// 		return this.state.drawerIsOpen;
		// };

		closeDrawer = () => {
      	this.drawer._root.close();
				this.setState({drawerIsOpen:false});
    };

    openDrawer = () => {
      	this.drawer._root.open();
				this.setState({drawerIsOpen:true});
    };

		goWebview = function (coupon){
				this.props.navigation.navigate("WebViewScreen",{coupon: coupon});
		};

		bannerPress = function (id){
				//console.log("bannerPress");
				var params = Util.getBannerParams(id);
				this.props.navigation.navigate("WebViewScreen",params);
		};

		loadSuggest = function (){
				this.setState({showLoading:true});
				Util.get("index.php?a=suggest",(response) =>{
						//this.state.suggestResult
						console.log(response);
						let towCouponsTemp = [];
						for(let i=0;i<response.data.length/2;i++){
								//response.data[i*2].onPress = this.goWebview(response.data[i*2]);
								//response.data[i*2+1].onPress = this.goWebview(response.data[i*2+1]);
								towCouponsTemp.push(
										[response.data[i*2],response.data[i*2+1]]
								);
								if(i>3){
										break;
								}
						}
						this.setState({showLoading:false,suggestResult:response.data,twoCouponsList:towCouponsTemp});
				},(error)=>{
						this.setState({showLoading:false});
						console.warn(error);
				});

		};

		goSearch = function (){
				let search = {};
				search.keyword = this.state.keyword;
				this.props.navigation.navigate("SearchScreen",{search: search});
		};

    render() {
        const {navigate} = this.props.navigation;

        return (
					<Drawer
						ref={(ref) => { this.drawer = ref; }}
						content={<SideBar navigation={this.props.navigation} />}
						onClose={()=>this.closeDrawer()}
						 >
						<Container>
							<Header style={styles.header} >
			          <Left>
									<Button transparent onPress={() => this.openDrawer()}>
										<Icon style={styles.white} name='menu' />
									</Button>
			          </Left>
			          <Body >
									<Title style={styles.headerTitle}>天天优惠</Title>
			          </Body>
			          <Right>

			          </Right>
			        </Header>
                <Content>
										<Swiper
												height={145}
												loop={true}
												autoplay={true}
												paginationStyle={{
														bottom: 10
												}}
										>
										<TouchableHighlight onPress={() => this.bannerPress(0)}>
											<Image
												style={styles.banner}
												source={{uri:'http://pega.oschina.io/storefiles/ttyouhui/slider/slider1.jpg'}}
        							/>
										</TouchableHighlight>
										<TouchableHighlight onPress={() => this.bannerPress(1)}>
											<Image
												style={styles.banner}
												source={{uri:'http://pega.oschina.io/storefiles/ttyouhui/slider/slider2.jpg'}}
        							/>
										</TouchableHighlight>
										<TouchableHighlight onPress={() => this.bannerPress(2)}>
											<Image
												style={styles.banner}
												source={{uri:'http://pega.oschina.io/storefiles/ttyouhui/slider/slider3.jpg'}}
        							/>
										</TouchableHighlight>
										</Swiper>
										<Item style={styles.searchBox}>
												<Input style={styles.searchInput}  placeholder='搜索看看'
																onChangeText={(keyword) => this.setState({keyword})}
																value={this.state.keyword}
																returnKeyType='done'
																onSubmitEditing={() => this.goSearch() }
												/>
												<Icon active name='search' onPress={() => this.goSearch() } />
										</Item>
                    { this.state.showLoading &&
                    <Spinner color='blue' />
                    }

										{this.state.twoItemsOneRow &&
											<List dataArray={this.state.twoCouponsList}
														renderRow={(twoCoupons) =>
															<ListItem style={styles.listItem}>
																	<TwoCoupons twoCoupons={twoCoupons} onPress={() => this.goWebview(twoCoupons[0])} onPress2={() => this.goWebview(twoCoupons[1])}></TwoCoupons>
															</ListItem>
													}
											>
											</List>
										}
										{!this.state.twoItemsOneRow &&
											<View style={{flex: 0, flexDirection: 'row', flexWrap: 'wrap'}}>
													<List dataArray={this.state.suggestResult}
			                          renderRow={(item) =>
			                            <ListItem>
			                                <CouponItem coupon={item} onPress={() => this.goWebview(item)} ></CouponItem>
			                            </ListItem>
			                        }
			                    >

			                    </List>
								      </View>
										}
                </Content>

            </Container>
					</Drawer>

        );
    }
};
